﻿Imports Microsoft.LightSwitch.Threading
Imports ComponentPro.Pdf
Imports ComponentPro.Pdf.Graphics
Imports DocumentToolkit.Client


Namespace LightSwitchApplication

    Public Class AnimalsListDetail
        Private _count As Integer

        Public Property Number() As Integer
            Get
                Return _count
            End Get
            Set(ByVal value As Integer)
                _count = value
            End Set
        End Property

        Private Sub MovementsAddAndEditNew_CanExecute(ByRef result As Boolean)
            ' Write your code here.
            'result = MovementsDialogHelper.CanAdd()
        End Sub

        Private Sub MovementsAddAndEditNew_Execute()
            ' Write your code here.
            'MovementsDialogHelper.AddEntity()
            Number = 1
            Dim newMovement As Movement = Me.Movements.AddNew()
            'Me.Animals.SelectedItem.Movements = newMovement
            Me.OpenModalWindow("MovementsDialog")
        End Sub

        Private Sub EditDialogOk_Execute()
            Me.CloseModalWindow("MovementsDialog")
            If Me.Movements.Count = 1 Then
                Me.Animals.SelectedItem.ActiveMovementDate = Me.Movements.SelectedItem.MovementDate
                Me.Animals.SelectedItem.ActiveMovementType = Me.Movements.SelectedItem.MovementType
                Me.Animals.SelectedItem.ActiveMovementID = Me.Movements.SelectedItem
                Me.Animals.SelectedItem.ActiveMovementPerson = Me.Movements.SelectedItem.Person
                Me.Animals.SelectedItem.ActiveMovementLocation = Me.Movements.SelectedItem.Location
                Me.Animals.SelectedItem.ActiveMovementShelter = Me.Movements.SelectedItem.Shelter
                Select Case Me.Movements.SelectedItem.MovementType.Id
                    Case 1
                        Me.Animals.SelectedItem.Archived = 1
                        'MsgBox("archived=True case 1")
                    Case 2 'Foster
                        Me.Animals.SelectedItem.Archived = 0
                    Case 3 'Transfer
                        Me.Animals.SelectedItem.Archived = 1
                    Case 4 'Escaped
                        Me.Animals.SelectedItem.Archived = 1
                    Case 5 'Reclaimed
                        Me.Animals.SelectedItem.Archived = 1
                    Case 6 'Stolen
                        Me.Animals.SelectedItem.Archived = 1
                    Case 7 'Released to the Wild
                        Me.Animals.SelectedItem.Archived = 1
                    Case 8 'Retailer
                        Me.Animals.SelectedItem.Archived = 0
                    Case 9 'Reservation
                        Me.Animals.SelectedItem.Archived = 0
                    Case 10 'Canceled reservation
                        Me.Animals.SelectedItem.Archived = 0
                    Case 11 'Trial Adoption
                        Me.Animals.SelectedItem.Archived = 1
                    Case 12 'Permanent Foster
                        Me.Animals.SelectedItem.Archived = 1
                    Case 14 'Returned
                        Me.Animals.SelectedItem.Archived = 0
                    Case Else
                        Me.Animals.SelectedItem.Archived = 1
                End Select
            Else
                For Each m In Me.Movements
                    If Me.Movements.SelectedItem.MovementDate > m.MovementDate Then
                        Me.Animals.SelectedItem.ActiveMovementDate = Me.Movements.SelectedItem.MovementDate
                        Me.Animals.SelectedItem.ActiveMovementType = Me.Movements.SelectedItem.MovementType
                        Me.Animals.SelectedItem.ActiveMovementID = Me.Movements.SelectedItem
                        Me.Animals.SelectedItem.ActiveMovementPerson = Me.Movements.SelectedItem.Person
                        Me.Animals.SelectedItem.ActiveMovementLocation = Me.Movements.SelectedItem.Location
                        Me.Animals.SelectedItem.ActiveMovementShelter = Me.Movements.SelectedItem.Shelter

                        Select Case Me.Movements.SelectedItem.MovementType.Id
                            Case 1
                                Me.Animals.SelectedItem.Archived = 1
                                'MsgBox("archived=True case 1")
                            Case 2 'Foster
                                Me.Animals.SelectedItem.Archived = 0
                            Case 3 'Transfer
                                Me.Animals.SelectedItem.Archived = 1
                            Case 4 'Escaped
                                Me.Animals.SelectedItem.Archived = 1
                            Case 5 'Reclaimed
                                Me.Animals.SelectedItem.Archived = 1
                            Case 6 'Stolen
                                Me.Animals.SelectedItem.Archived = 1
                            Case 7 'Released to the Wild
                                Me.Animals.SelectedItem.Archived = 1
                            Case 8 'Retailer
                                Me.Animals.SelectedItem.Archived = 0
                            Case 9 'Reservation
                                Me.Animals.SelectedItem.Archived = 0
                            Case 10 'Canceled reservation
                                Me.Animals.SelectedItem.Archived = 0
                            Case 11 'Trial Adoption
                                Me.Animals.SelectedItem.Archived = 1
                            Case 12 'Permanent Foster
                                Me.Animals.SelectedItem.Archived = 1
                            Case 14 'Returned
                                Me.Animals.SelectedItem.Archived = 0
                            Case Else
                                Me.Animals.SelectedItem.Archived = 1
                        End Select
                    End If
                Next
            End If

            Number = Nothing
        End Sub

        Private Sub EditDialogCancel_Execute()
            Me.CloseModalWindow("MovementsDialog")
            If Number = 1 Then
                Me.Movements.SelectedItem.Delete()
            End If
            Number = Nothing
        End Sub

        Private Sub MovementsEditSelected_CanExecute(ByRef result As Boolean)
            ' Write your code here.
            'result = MovementsDialogHelper.CanEditSelected()
        End Sub

        Private Sub MovementsEditSelected_Execute()
            ' Write your code here.
            Number = Nothing
            Me.OpenModalWindow("MovementsDialog")
        End Sub

        Private Sub AnimalsListDetail_InitializeDataWorkspace(saveChangesTo As List(Of Microsoft.LightSwitch.IDataService))
            ' Write your code here.
            Me.AnimalArchived = 2
            If Application.User.HasPermission(CanEmail) Then
                Me.FindControl("SendAnEmail").IsVisible = True
            Else
                Me.FindControl("SendAnEmail").IsVisible = False
            End If

            If Application.User.HasPermission(CanUpdateMedia) Then
                Me.FindControl("MediaCollection_DeleteSelected").IsVisible = True
                Me.FindControl("Upload").IsVisible = True
            Else
                Me.FindControl("MediaCollection_DeleteSelected").IsVisible = False
                Me.FindControl("Upload").IsVisible = False
            End If

            If Application.User.HasPermission(Permissions.CanUpdateMovements) Then
                Me.FindControl("MovementsAddAndEditNew").IsVisible = True
                Me.FindControl("MovementsEditSelected").IsVisible = True
                Me.FindControl("Movements_DeleteSelected").IsVisible = True
            Else
                Me.FindControl("MovementsAddAndEditNew").IsVisible = False
                Me.FindControl("MovementsEditSelected").IsVisible = False
                Me.FindControl("Movements_DeleteSelected").IsVisible = False
            End If

            If Application.User.HasPermission(Permissions.CanUpdateVaccines) Then
                Me.FindControl("Vaccines_AddAndEditNew").IsVisible = True
                Me.FindControl("Vaccines_EditSelected").IsVisible = True
                Me.FindControl("Vaccines_DeleteSelected").IsVisible = True
            Else
                Me.FindControl("Vaccines_AddAndEditNew").IsVisible = False
                Me.FindControl("Vaccines_EditSelected").IsVisible = False
                Me.FindControl("Vaccines_DeleteSelected").IsVisible = False
            End If

            If Application.User.HasPermission(Permissions.CanCreateLogs) Then
                Me.FindControl("Logs_AddAndEditNew").IsVisible = True
            Else
                Me.FindControl("Logs_AddAndEditNew").IsVisible = False
            End If

            If Application.User.HasPermission(Permissions.CanUpdateAnimals) Then
                Me.FindControl("Logs_AddAndEditNew").IsVisible = True
                Me.FindControl("Logs_EditSelected").IsVisible = True
                Me.FindControl("Logs_DeleteSelected").IsVisible = True
            Else
                Me.FindControl("Logs_EditSelected").IsVisible = False
                Me.FindControl("Logs_DeleteSelected").IsVisible = False
            End If
        End Sub

        Private Sub AnimalsListDetail_Created()
            Dim Upload = Me.FindControl("Upload")
            AddHandler Upload.ControlAvailable, AddressOf Upload_ControlAvailable

            Dim Merge = Me.FindControl("Merge")
            AddHandler Merge.ControlAvailable, AddressOf Merge_ControlAvailable

        End Sub

        Private Sub Upload_ControlAvailable(sender As Object, e As ControlAvailableEventArgs)
            RemoveHandler Me.FindControl("Upload").ControlAvailable, AddressOf Upload_ControlAvailable
            Dim Button = DirectCast(e.Control, Button)
            AddHandler Button.Click, AddressOf Upload_Click

        End Sub

        Private Sub Merge_ControlAvailable(sender As Object, e As ControlAvailableEventArgs)
            RemoveHandler Me.FindControl("Merge").ControlAvailable, AddressOf Merge_ControlAvailable
            Dim Button = DirectCast(e.Control, Button)
            AddHandler Button.Click, AddressOf Merge_Click

        End Sub

        Private Sub Upload_Click(sender As Object, e As System.Windows.RoutedEventArgs)
            Dim result As FileInfo = Nothing
            Try
                Dispatchers.Main.Invoke(
                Sub()
                    Dim dlg = New OpenFileDialog()
                    dlg.Filter = "Mutt Scout Images|*.pdf;*.xps;*.jpg;*.png"
                    If dlg.ShowDialog = True Then
                        Dim file = dlg.File
                        If Not file Is Nothing Then
                            Me.Details.Dispatcher.BeginInvoke(
                                Sub()
                                    Dim bData As Byte()
                                    Dim br As BinaryReader = New BinaryReader(file.OpenRead())
                                    Try
                                        'Dim reader = DocumentReader.Create(file)
                                        'Using reader
                                        'Dim document = Me.MediaCollection.AddNew
                                        'document.FileName = file.Name
                                        'document.File = reader.ToBinary

                                        'If reader.RequiresConversionToXps Then
                                        '' conversion needed, get the XPS binary
                                        'document.FileXps = reader.ToXpsBinary
                                        'End If
                                        'End Using
                                        'End Sub)

                                        bData = br.ReadBytes(br.BaseStream.Length)
                                        'Dim ms As MemoryStream = New MemoryStream(bData, 0, bData.Length)

                                        Dim document = Me.MediaCollection.AddNew()
                                        document.FileName = file.Name
                                        document.File = bData
                                    Catch ex As Exception
                                        Dim xerr = Me.DataWorkspace.ApplicationData.ErrorsSet.AddNew
                                        xerr.ErrorDescription = ex.Message
                                    Finally
                                        bData = Nothing
                                        br.Dispose()
                                        file = Nothing
                                        dlg = Nothing
                                    End Try
                                End Sub)
                        End If
                    End If
                End Sub)
            Catch ex As Exception
                Dim xerr = Me.DataWorkspace.ApplicationData.ErrorsSet.AddNew
                xerr.ErrorDescription = ex.Message
            Finally
                result = Nothing
            End Try

        End Sub

        Private Sub Test_Execute()
            ' Write your code here.
            Dispatchers.Main.Invoke(
            Sub()
                Try

                    Dim stream3 As New MemoryStream
                    Dim newPDF As New PdfDocument()
                    If Me.MediaCollection.Count > 1 Then
                        Dim stream1 As Stream = New MemoryStream(Me.MediaCollection.FirstOrDefault.File)
                        For Each xfile In Me.MediaCollection
                            If xfile.Id <> Me.MediaCollection.FirstOrDefault.Id Then
                                Dim xdata = xfile.File
                                Dim stream2 As Stream = New MemoryStream(xdata)
                                PdfDocumentBase.Merge(newPDF, stream1, stream2)
                                newPDF.Save(stream3)
                                'newPDF.Close()
                                stream2.Close()
                            End If
                        Next
                        Me.Details.Dispatcher.BeginInvoke(
                            Sub()
                                Dim memoryStream As New MemoryStream()

                                Dim doc As New PdfDocument()

                                Dim page As PdfPage = doc.Pages.Add()
                                Dim g As PdfGraphics = page.Graphics

                                Dim font As PdfFont = New PdfStandardFont(PdfFontFamily.Helvetica, 14, PdfFontStyle.Bold)
                                'Dim point As New PointF(50, 0)
                                g.DrawString("My Text", font, PdfBrushes.DarkBlue, 50, 0)
                                doc.Save(memoryStream)







                                Dim reader = DocumentReader.Create(memoryStream)
                                Using reader
                                    Dim document = Me.MediaCollection.AddNew
                                    document.FileName = "Combined.pdf"
                                    document.File = reader.ToBinary
                                End Using

                                stream1.Close()
                                stream3.Close()
                                newPDF.Close()
                                doc.Close()
                            End Sub)
                    End If

                Catch ex As Exception
                    MessageBox.Show(ex.ToString)
                End Try
            End Sub)

        End Sub

        Private Sub Test_Click(sender As Object, e As System.Windows.RoutedEventArgs)
            Dispatchers.Main.Invoke(
Sub()
    Dim dlg As New SaveFileDialog()

    dlg.Filter = "PDF files (.pdf)|*.pdf|All Files (*.*)|*.*"
    dlg.FilterIndex = 1


    If dlg.ShowDialog() = True Then
        Dim message As String = Nothing

        Try
            Using fileStream As Stream = dlg.OpenFile()
                Dim name As String = Me.Animals.SelectedItem.Name
                'Dim breed As String = Nothing
                'If IsNothing(Me.Animals.SelectedItem.Crossbreed.Title) Then
                'Breed = Me.Animals.SelectedItem.Breed.Title
                'Else
                'Breed = Me.Animals.SelectedItem.Breed.Title & " & " & Me.Animals.SelectedItem.Crossbreed.Title
                'End If


                Const fontStyle As PdfFontStyle = PdfFontStyle.Regular
                Const fontSize As Single = 12.0F
                Me.Details.Dispatcher.BeginInvoke(
    Sub()
        Dim document As New PdfDocument
        ' Add a page
        Dim page As PdfPage = document.Pages.Add()

        ' Create a solid brush
        Dim brush As PdfBrush = New PdfSolidBrush(New PdfColor(0, 0, 0))

        ' Set the font
        Dim font As PdfFont = New PdfStandardFont(PdfFontFamily.Helvetica, fontSize, fontStyle)
        Dim ximage As New MemoryStream(Me.Animals.SelectedItem.Photo)
        Dim image As New PdfBitmap(ximage)
        Dim xsize As System.Drawing.SizeF
        xsize.Height = 100
        xsize.Width = 100

        ' Draw the text
        page.Graphics.DrawString("Name: " & name, font, brush, New System.Drawing.PointF(30, 30))
        page.Graphics.DrawString("Breed: ", font, brush, New System.Drawing.PointF(30, 60))

        page.Graphics.DrawImage(image, New System.Drawing.PointF(300, 30), xsize)
        document.FileStructure.CrossReferenceType = PdfCrossReferenceType.CrossReferenceTable

        document.FileStructure.Version = PdfVersion.Version14

        Dim memoryStream As New MemoryStream()
        document.Save(memoryStream)
        Dim reader = DocumentReader.Create(memoryStream)
        Using reader
            Dim doc = Me.MediaCollection.AddNew
            doc.FileName = "Combined.pdf"
            doc.File = reader.ToBinary
        End Using
        memoryStream.Close()


        ' Close the document.
        document.Close()
    End Sub)
                'document.Save(fileStream)
            End Using




            message = "File saved successfully."

        Catch ex As Exception
            MessageBox.Show("Error saving PDF file. Error: " & ex.Message)
        End Try

        'lblMessage.Content = message
    End If

End Sub)
        End Sub

        Private Sub Merge_Click(sender As Object, e As System.Windows.RoutedEventArgs)
            Dim dlg As New SaveFileDialog()

            dlg.Filter = "PDF files (.pdf)|*.pdf|All Files (*.*)|*.*"
            dlg.FilterIndex = 1


            If dlg.ShowDialog() = True Then
                Dim message As String = Nothing

                Try
                    Using fileStream As Stream = dlg.OpenFile()
                        Dim newPDF As New PdfDocument()
                        For Each xfile In Me.MediaCollection
                            PdfDocumentBase.Merge(newPDF, xfile.File)
                        Next
                        newPDF.Save(fileStream)
                        newPDF.Close()

                    End Using


                    message = "File saved successfully."

                Catch ex As Exception
                    MessageBox.Show("Error saving PDF file. Error: " & ex.Message)
                End Try

                'lblMessage.Content = message
            End If

        End Sub


        Private Sub SendAnEmail_Execute()
            ' Write your code here.
            ' create a new ServiceOPeratorSendEmail object.

            'Dim email As Email = DataWorkspace.ApplicationData.Emails.AddNew()
            Dim email As Email = Me.Emails.AddNew()
            Me.OpenModalWindow("EmailMessage")
            email.FromEmailAddress = "themuttscouts@gmail.com"
            ' add values to the properties of the new ServiceOPeratorSendEmail object.
            'email.FromEmailAddress = "onlyouknowho@gmail.com"
            'email.ToEmailAddresses = "frank.h.meyers@gmail.com"
            'email.ToEmailAddresses = Me.Emails.SelectedItem.ToEmailAddresses
            'email.Subject = "This is an email from LightSwitch"
            'email.Subject = Me.Emails.SelectedItem.Subject
            'email.Message = "Hello World"
            'email.Message = Me.Emails.SelectedItem.Message
            email.IsHTML = False
            email.Animal = Me.Animals.SelectedItem
            ' tell the application to save the changes which will fire the 
            ' ServiceOperationSendEmails_Inserting method on the server.

        End Sub

        Private Sub Send_Execute()
            ' Write your code here.
            Me.CloseModalWindow("EmailMessage")
            DataWorkspace.ApplicationData.SaveChanges()
        End Sub

        Private Sub Cancel_Execute()
            ' Write your code here.
            Me.CloseModalWindow("EmailMessage")
            Me.Emails.SelectedItem.Delete()
        End Sub

        Private Sub SendAnEmail_CanExecute(ByRef result As Boolean)
            If Application.User.HasPermission(CanEmail) Then
                result = True
            Else
                result = False
            End If
        End Sub

    End Class

End Namespace
